<?php
/**
 * 达人秀 Model
 * User: lz
 * Date: 2016/1/27
 * Time: 12:17
 * return ShowModel
 */

class ShowModel extends BaseModel {
    var $table  = 'show';
    var $prikey = 'show_id';
    var $_name  = 'show';

    /**
     * 写入达人秀数据
     * @param $user_id
     * @param $description
     * @param $images
     * @return bool
     */
    public function publish($user_id,$description,$images){
        $sql = "INSERT INTO ".DB_PREFIX_NEW."show (user_id,description,images,add_time)
                VALUES ('".$user_id."','".$description."','".$images."','".time()."')";
        $flag = $this->query($sql);
        if($flag){
            return mysql_insert_id();//获取最后插入的id
        } else {
            return $flag;
        }
    }

    /**
     * 删除达人秀
     * @param $show_id
     * @return bool
     */
    public function  delShow($show_id,$user_id){
        $this->begin();
        try{
            //删除达人秀
            $sql = "DELETE FROM ".DB_PREFIX_NEW."show WHERE user_id='{$user_id}' AND show_id='{$show_id}'";
            $this->query($sql);
            $affect=mysql_affected_rows();
            if(!$affect){
                throw new Exception('删除达人秀失败');
            }
            //获取话题的id
            $sql = "SELECT topic_id FROM ".DB_PREFIX_NEW."showid_topic where show_id='{$show_id}'";
            $topic_data = $this->getAll($sql);
            $topic_num=pluck($topic_data,'topic_id');
            //获取话题对应的达人秀的数量
            $sql = "SELECT topic_id,count(*) as num from ".DB_PREFIX_NEW."showid_topic WHERE topic_id IN ( ".implode (',',$topic_num)." ) group by topic_id ORDER BY field(topic_id,".implode (',', $topic_num).")";
            $data = $this->getAll($sql);
            foreach($data as $value){
                //删除达人秀对应的话题关系
                $sql = "DELETE FROM ".DB_PREFIX_NEW."showid_topic WHERE  show_id='{$show_id}' AND topic_id='{$value['topic_id']}'";
                $this->query($sql);
                $affect =mysql_affected_rows();
                if(!$affect){
                    throw new Exception('删除对应关系失败');
                }
                //删除达人秀对应的话题
                if($value['num']<=1){
                    $sql = "DELETE FROM ".DB_PREFIX_NEW."topic WHERE topic_id='{$value['topic_id']}'";
                    $this->query($sql);
                    $affect=mysql_affected_rows();
                    if(!$affect){
                        throw new Exception('删除话题失败');
                    }
                }
            }
            //删除达人秀对应的商品
            $sql = "SELECT goods_id FROM ".DB_PREFIX_NEW."showid_goods  WHERE show_id='".$show_id."'";
            $goods_data =$this->getAll($sql);
            //$num= array_column($goods_data,'goods_id');
            $goods_num=pluck($goods_data,'goods_id');
            $sql = "DELETE FROM ".DB_PREFIX_NEW."showid_goods WHERE goods_id IN(".implode (',',$goods_num).")";
            $this->query($sql);
            $affect =mysql_affected_rows();
            if(!$affect){
                throw new Exception('关联商品失败');
            }
            //删除达人秀对应的评论
            $sql = "SELECT id FROM ".DB_PREFIX_NEW."show_comment  WHERE user_id={$user_id} AND show_id='".$show_id."'";
            $comments_data = $this->getAll($sql);
            if($comments_data){
                //$ids= array_column($comments_data,'id');
                $comments_num=pluck($comments_data,'id');
                $sql = "DELETE FROM ".DB_PREFIX_NEW."show_comment WHERE id IN(".implode (',',$comments_num).")";
                $this->query($sql);
                $affect =mysql_affected_rows();
                if(!$affect){
                    throw new Exception('删除评论失败');
                }
            }
            $this->commit();
            return true;
        }catch(Exception $e){
            $this->rollback();
            return false;
            //exit($e->getMessage());
        }
    }

    /**
     * 添加达人秀话题
     * @param $show_id
     * @param $topic
     * @return bool
     */
    public function topic($show_id,$topic) {
        $topic = str_replace('#','',$topic);
        $topic = explode(',',$topic);
        foreach($topic as $val){
            //检测数据库中有没有该话题
            $info = $this->checkTopic(addslashes($val));
            if($info) {
                $topic_id = $info['topic_id'];
                //更新show 表中的 show_num
                $sql = "UPDATE ".DB_PREFIX_NEW."topic SET show_num=show_num+1 WHERE topic_id='".$info['topic_id']."'";
                $this->query($sql);
            } else {
                //插入新的话题
                $sql = "INSERT INTO ".DB_PREFIX_NEW."topic (topic,add_time,show_num)
                VALUES ('".addslashes($val)."','".time()."','1')";
                $flag = $this->query($sql);
                $topic_id = mysql_insert_id();//获取最后插入的id
            }

            //添加showid_topic
            $sql = "INSERT INTO ".DB_PREFIX_NEW."showid_topic (show_id,topic_id)
                VALUES ('".$show_id."','".$topic_id."')";
            $this->query($sql);
        }
    }

    /**
     * 关联商品
     * @param $show_id
     * @param $goods_id
     */
    public function goods($show_id,$goods_id){
        $goods = explode(',',$goods_id);
        foreach($goods as $val){
            $sql = "INSERT INTO ".DB_PREFIX_NEW."showid_goods (show_id,goods_id)
                VALUES ('".$show_id."','".$val."')";
            $this->query($sql);
        }
    }

    /**
     * 检测话题是否存在
     * @param $topic
     * @return mixed
     */
    public function checkTopic($topic){
        $sql = "SELECT topic_id FROM ".DB_PREFIX_NEW."topic WHERE topic='".$topic."'";
        return $this->getRow($sql);
    }

    /**
     * 获取首页达人秀列表
     * @param $offset
     * @param $size
     * @param $common
     * @param $user_id
     */
    public function getList($offset,$size,$common,$user_id){
        //获取达人秀列表
        $sql = "SELECT show_id,a.user_id,a.images,a.description,a.favorite,a.comments,a.add_time,b.profession,b.user_name,b.portrait,b.is_star
                FROM ".DB_PREFIX_NEW."show a LEFT JOIN ".DB_PREFIX."member b ON a.user_id=b.user_id
                WHERE a.if_show = 0 ORDER BY a.add_time DESC LIMIT {$offset},{$size}";
        $list = $this->getAll($sql);
        foreach($list as $key=>$val){
            //检测当前用户是否喜欢
            $val['like'] = 0;
            if($user_id) {
                $sql = "SELECT show_id FROM ".DB_PREFIX_NEW."showid_favorite WHERE show_id={$val['show_id']} AND user_id={$user_id}";
                $favorite = $this->getRow($sql);
                if($favorite) {
                    $val['like'] = 1;
                }
            }
            //获取2条最新评论
            $sql = "SELECT b.user_name,content FROM ".DB_PREFIX_NEW."show_comment a LEFT JOIN ".DB_PREFIX."member b ON a.user_id=b.user_id
                    WHERE show_id = '{$val['show_id']}' ORDER BY a.add_time DESC LIMIT 2";
            $comment = $this->getAll($sql);
            //获取话题id
            $ids = $this->getTopicIdByShowId($val['show_id']);
            //获取话题内容
            $topic = $this->getTopic($ids);
            //获取2个相关商品
            $sql = "SELECT goods_id FROM ".DB_PREFIX_NEW."showid_goods WHERE show_id='{$val['show_id']}' LIMIT 2";
            $goods_id = $this->getAll($sql);
            $goods = array();
            foreach($goods_id as $v){
                $sql = "SELECT goods_id,goods_name,brand,price,market_price,default_image FROM ".DB_PREFIX."goods WHERE goods_id='{$v['goods_id']}'";
                $goodsInfo = $this->getRow($sql);
                $goodsInfo['default_image'] = $common->isMySelfImage($goodsInfo['default_image'], DISCOVERY_GOODS_IMG);
                $goods[] = $goodsInfo;
            }
            $val['images'] = $val['images'] ? QINIU_URL.$val['images'] : '';
            $arr = getimagesize($val['images']);
            $val['images_width'] = $arr[0];
            $val['images_height'] = $arr[1];
            $val['portrait'] = $val['portrait'] ? QINIU_URL.$val['portrait'] : '';
            $val['comment'] = $comment;
            $val['topics'] = $topic;
            $val['goods'] = $goods;
            $list[$key]=$val;
        }
        return $list;
    }

    /**
     * 获取一条详情
     * @param $show_id      //达人秀id
     * @param $user_id      //用户id
     * @param $common
     * @return mixed
     */
    public function oneDetail($show_id,$common,$user_id){
        //获取达人秀里面的信息
        $sql = "SELECT a.show_id,a.user_id,a.images,a.description,a.favorite,a.comments,a.add_time,a.add_time,b.profession,b.user_name,b.portrait,b.is_star
                FROM ".DB_PREFIX_NEW."show a LEFT JOIN ".DB_PREFIX."member b ON a.user_id=b.user_id
                WHERE a.if_show = 0 and show_id='{$show_id}' ORDER BY a.sort DESC ";
        $data = $this->getRow($sql);
        if(empty($data))
        {
            return $list=array ();
        }
//        //检测当前用户是否喜欢
        $val['like'] = 0;
        if($user_id) {
            $sql = "SELECT show_id FROM ".DB_PREFIX_NEW."showid_favorite WHERE show_id='{$show_id}'  AND user_id='{$user_id}'";
            $favorite = $this->getRow($sql);
            if($favorite) {
                $val['like'] = 1;
            }
        }
        //获取2条最新评论
        $sql = "SELECT b.user_name,content FROM ".DB_PREFIX_NEW."show_comment a LEFT JOIN ".DB_PREFIX."member b ON a.user_id=b.user_id
                    WHERE show_id = '{$show_id}' ORDER BY a.add_time DESC LIMIT 2";
        $comment= $this->getAll($sql);
        //获取2个相关商品
        $sql = "SELECT goods_id FROM ".DB_PREFIX_NEW."showid_goods WHERE show_id='{$show_id}' LIMIT 2";
        $goods_id = $this->getAll($sql);
        if(!empty($goods_id)){
            $goods = array();
            foreach ( $goods_id as $temp ) $ids[]= $temp['goods_id'];
            $sql = "SELECT goods_id,goods_name,brand,price,market_price,default_image FROM ".DB_PREFIX."goods WHERE goods_id in ( ".implode (',', $ids)." )";
            foreach ( $this->getAll($sql) as $index => $array )
            {
                $array ['default_image'] = $common->isMySelfImage($array['default_image'], DISCOVERY_GOODS_IMG);
                $goods [$index] = $array;
            }
        }else{
                $goods=array();
        }
        $val['show_id']=$data['show_id'];
        $val['user_id']=$data['user_id'];
        $val['user_name']=$data['user_name'];
        $val['description']=$data['description'];
        $val['profession']=$data['profession'];
        $val['favorite']=$data['favorite'];
        $val['comments']=$data['comments'];
        $val['images'] = $data['images'] ? QINIU_URL.$data['images'].'_640_640_2_85.jpg' : '';
        $val['portrait'] = $data['portrait'] ? QINIU_URL.$data['portrait'] : '';
        $val['add_time']=$data['add_time'];
        $val['comment'] = $comment;
        $val['goods'] = $goods;
        $list[]=$val;
            return $list;
    }
    //获取达人秀的id
    public function getShowId($topic_id){
        $sql = "SELECT show_id FROM ".DB_PREFIX_NEW."showid_topic where topic_id='{$topic_id}'";      //查询达人秀的id
        $showid = $this->getAll($sql);
        return $showid;
    }
    /**
     * 点击获取更多信息
     * @param $show_id      //达人秀id
     * @return array
     */
    public function getShowList($show_id){
                 foreach($show_id as $k=>$v){        //判断达人秀的数量如果大于两个 显示达人秀列表页，否则显示详情页
                     $sql = "SELECT show_id,images FROM ".DB_PREFIX_NEW."show where show_id='{$v['show_id']}' order by add_time desc";
                     $showdetail = $this->getAll($sql);
                     foreach($showdetail as $k=>$v){
                         $showdetails['show_id']=$v['show_id'];
                         $showdetails['images']=$v['images']? QINIU_URL.$v['images'].'_320_320_2_85.jpg' : '';
                         $details[]=$showdetails;
                     }
                 }

          return $details;
      }
    //根据达人秀id拿到话题的id
    public function getTopicIdByShowId($show_id){
        $sql = "SELECT topic_id FROM ".DB_PREFIX_NEW."showid_topic where show_id={$show_id} LIMIT 5";
        $data = $this->getAll($sql);
        return $data;
    }
    //获取话题内容
    public function getTopic($topic_id){
        foreach ( $topic_id as $temp ) $ids[]= $temp['topic_id'];
        $sql = "SELECT topic_id,topic FROM ".DB_PREFIX_NEW."topic where topic_id in ( ".implode (',', $ids)." )";
        $data = $this->getAll($sql);
        return $data;
    }
    //获取话题ID
    public function getTopicId(){
        $sql=  "SELECT topic_id FROM ".DB_PREFIX_NEW."recommend_topic order by sort desc LIMIT 10";
        $data=$this->getAll($sql);
        return $data;
    }
    //通过话题id查找话题名称
    public function getTenTopic($topic_id){

        foreach ( $topic_id as $temp ) $ids[]= $temp['topic_id'];
        $sql = "SELECT topic FROM ".DB_PREFIX_NEW."topic WHERE `topic_id` in ( ".implode (',', $ids)." )";
        foreach ( $this->getAll($sql) as $index => $array )
        {
            $tentopic[$index] = $array;
        }
        return $tentopic;
    }
    /**
     *
     * 获取达人秀话题
     * @param $offset
     * @param $size
     * @return mixed
     */
    public function getTopicList($offset,$size){
        //获取达人秀列表
        $sql = "SELECT topic_id,topic,show_num FROM ".DB_PREFIX_NEW."topic ORDER BY add_time DESC LIMIT {$offset},{$size}";
        $topic = $this->getAll($sql);
        foreach($topic as $key=>$val) {
            $sql = "SELECT b.show_id,images FROM ".DB_PREFIX_NEW."showid_topic a
                    LEFT JOIN ".DB_PREFIX_NEW."show b ON a.show_id=b.show_id WHERE a.topic_id='{$val['topic_id']}' LIMIT 3";
            $images = $this->getAll($sql);
            foreach($images as $k=>$v){
                $v['images'] = $v['images'] ? QINIU_URL.$v['images'].'_640_640_2_85.jpg' : '';
                $images[$k]=$v;
            }
            $val['show'] = $images;
            $topic[$key]=$val;
        }
        return $topic;
    }

    /**
     * 达人秀添加喜欢
     * @param $user_id
     * @param $show_id
     * @return bool
     */
    public function addFavorite($user_id,$show_id){
        $sql = "INSERT INTO ".DB_PREFIX_NEW."showid_favorite (show_id,user_id,add_time)
                VALUES ({$show_id},{$user_id},".time().")";
        $res1 = $this->query($sql);
        $sql = "UPDATE ".DB_PREFIX_NEW."show SET favorite=favorite+1 WHERE show_id='".$show_id."'";
        $res2 = $this->query($sql);
        if($res1 && $res2) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据用户查找是否喜欢达人秀
     * @param $user_id
     * @param $show_id
     * @return bool
     */
    public function getFavorite($show_id,$user_id){
        $sql = "SELECT count(*) FROM ".DB_PREFIX_NEW."showid_favorite where show_id='{$show_id}' AND user_id='{$user_id}'";
        $data=$this->getOne($sql);
        return $data;
    }
    /**
     * 达人秀取消喜欢
     * @param $user_id
     * @param $show_id
     * @return bool
     */
    public function delFavorite($user_id,$show_id){
        $sql = "DELETE FROM ".DB_PREFIX_NEW."showid_favorite WHERE user_id='{$user_id}' AND show_id='{$show_id}'";
        $res1 = $this->query($sql);
        $sql = "UPDATE ".DB_PREFIX_NEW."show SET favorite=favorite-1 WHERE show_id='".$show_id."'AND favorite>0";
        $res2 = $this->query($sql);
        if($res1 && $res2) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取达人秀评论接口
     * @param $show_id
     * @return mixed
     */
    public function getComments($show_id){
        $sql = "SELECT a.id,a.show_id,b.user_id,b.user_name,a.content,a.add_time,b.portrait,b.profession,b.is_star FROM ".DB_PREFIX_NEW."show_comment a
                LEFT JOIN ".DB_PREFIX."member b ON a.user_id=b.user_id  WHERE a.show_id='{$show_id}' ORDER BY a.add_time DESC";
        $comment = $this->getAll($sql);
        if($comment) {
            foreach($comment as $key=>$val) {
                $val['portrait'] = $val['portrait'] ? QINIU_URL.$val['portrait'] : '';
                $val['is_star'] = $val['is_star']?1:0;
                $comment[$key]=$val;
            }
        }
        return $comment;
    }

    /**
     * 添加评论接口
     * @param $user_id
     * @param $show_id
     * @param $content
     * @return bool
     */
    public function addComments($user_id,$show_id,$content){
        $sql = "INSERT INTO ".DB_PREFIX_NEW."show_comment (user_id,show_id,content,add_time)
                VALUES ({$user_id},{$show_id},'".addslashes($content)."',".time().")";
        $res1 =  $this->query($sql);
        $sql = "UPDATE ".DB_PREFIX_NEW."show SET comments=comments+1 WHERE show_id='".$show_id."'";
        $res2 = $this->query($sql);
        if($res1 && $res2) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 返回达人自己的达人秀数据
     * @param $user_id
     * @param $offset
     * @param $size
     * @return mixed
     */
    public function getMyDarenShow($user_id,$offset,$size){
        $sql = "SELECT show_id,images FROM ".DB_PREFIX_NEW."show WHERE user_id='{$user_id}'ORDER BY add_time DESC LIMIT {$offset},{$size}";
        $show = $this->getAll($sql);
        if($show) {
            foreach($show as $key=>$val) {
                $val['images'] = $val['images'] ? QINIU_URL.$val['images'].'_320_320_2_85.jpg' : '';
                $show[$key]=$val;
            }
        }
        $sql = "SELECT count(*) as total FROM ".DB_PREFIX_NEW."show WHERE user_id='{$user_id}'";
        $total = $this->getRow($sql);
        $data = array('total'=>$total['total'],'show'=>$show);
        return $data;
    }

    // @TODO 假设$user_id 一定为达人 is_star = 1
    public function getMyTopicList($offset,$size,$user_id){
        // 获取用户发布的所有达人秀
        $sql = "SELECT `show_id`,`images` FROM ".DB_PREFIX_NEW."show WHERE `user_id`={$user_id}";
        foreach ( $this->getAll($sql) as $temp ) $shows [ $temp ['show_id'] ] = $temp;
        if(!empty($shows)){
            // 达人秀跟话题的映射关系
            $sql = "SELECT * FROM ".DB_PREFIX_NEW."showid_topic WHERE `show_id` IN ( ". implode ( ',', array_keys ( $shows ) ) ." )";
            foreach ( $this->getAll($sql) as $temp ) $topicMaps [ $temp ['topic_id'] ] []  = $temp ['show_id'];
            // 所有用户话题
            $sql = "SELECT * FROM ".DB_PREFIX_NEW."topic WHERE `topic_id` IN (". implode ( ',', array_keys ( $topicMaps )).")ORDER BY add_time DESC LIMIT {$offset},{$size}";
            foreach ( $this->getAll($sql) as $index => $temp )
            {
                $show = array();
                $total = count ( $topicMaps[ $temp ['topic_id'] ] );
                if ( $total )
                {
                    for ($i=0,$total=$total>2?3:$total;$i<$total;$i++ ){
                        $show_id = $topicMaps[ $temp ['topic_id'] ][$i];
                        $image = $shows[$show_id] ? QINIU_URL.$shows[$show_id]['images'] : '';
                        $show[] = array ( 'show_id' =>$show_id, 'images' => $image);
                    }
                }
                $data [$index] = array (
                    'topic_id' => $temp ['topic_id'],
                    'total' => $i,
                    'topic' => $temp ['topic'],
                    'show' => $show,
                );

            }
        }else{
                $data=array();
        }
        return $data;
        /*
        //获取达人秀列表
        $sql = "SELECT b.topic_id FROM ".DB_PREFIX_NEW."show a
                LEFT JOIN ".DB_PREFIX_NEW."showid_topic b on a.show_id=b.show_id
                WHERE a.user_id={$user_id} GROUP BY b.topic_id LIMIT {$offset},{$size}";
        $res = $this->getAll($sql);
        $data = array();
        foreach($res as $key=>$val) {
            $sql = "SELECT topic FROM ".DB_PREFIX_NEW."topic WHERE topic_id='{$val['topic_id']}'";
            $topic = $this->getRow($sql);
            $sql = "SELECT a.show_id,a.images FROM ".DB_PREFIX_NEW."show a
                    LEFT JOIN ".DB_PREFIX_NEW."showid_topic b on a.show_id=b.show_id
                    WHERE a.user_id='{$user_id}' AND b.topic_id = '{$val['topic_id']}' GROUP BY a.show_id LIMIT 3";
            $show = $this->getAll($sql);
            foreach($show as $k=>$v) {
                $v['images'] = $v['images'] ? QINIU_URL.$v['images'] : '';
                $show[$k]=$v;
            }
            $val['total'] = count($show);
            $val['topic']=$topic['topic'];
            $val['show'] = $show;
            //$data[$key]['topic'] = $topic['topic'];
            $data[$key] = $val;

        }
        */

    }

}